package sseemitter

import (
	"encoding/json"
	"log"
	"reflect"
	"sync"
)

type SSEEmitter struct {
	clients   map[chan string]any
	clientsMu sync.RWMutex
}

// NewSSEmitter 创建接连管理对象
func NewSSEmitter() *SSEEmitter {
	return &SSEEmitter{
		clients: make(map[chan string]any),
	}
}

// AddClient 添加客户端连接
func (s *SSEEmitter) AddClient(client chan string) {
	s.clientsMu.Lock()
	defer s.clientsMu.Unlock()
	s.clients[client] = struct{}{}
}

// RemoveClient 删除客户端
func (s *SSEEmitter) RemoveClient(client chan string) {
	s.clientsMu.Lock()
	defer s.clientsMu.Unlock()
	delete(s.clients, client)
}

// Event 发送事件
func (s *SSEEmitter) Event(event any) {
	typeOf := reflect.TypeOf(event)
	log.Println(typeOf.Name())
	jsonData, _ := json.Marshal(event)
	for client := range s.clients {
		client <- string(jsonData)
	}
}
